﻿using AmiDraw.Editor.ViewModel;
using AmiDraw.Lib.Factory;
using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace AmiDraw.Editor.Converters
{
    public class PathToBitMapConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string path;
            if (value is null)
            {
                path = @"/Resources/noimage.png";
            }
            else
            {
                if (string.IsNullOrEmpty(value as string))
                {
                    path = @"/Resources/noimage.png";
                }
                else
                {
                    path = value as string;
                    path = PathFactory.GetResImagePath(PackEditViewModel.instance.PackInfo.Name,path,Lib.ResultQueryMode.Editor);
                    
                }
            }
            try
            {
                return GetBitmapImage(path);
            }
            catch (Exception)
            {
                path = @"/Resources/noimage.png";

                return new BitmapImage(new Uri(path, UriKind.RelativeOrAbsolute));
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }

        private BitmapImage GetBitmapImage(string value)
        {
             BitmapImage bitmapImage = null;
            using (BinaryReader reader = new BinaryReader(File.Open(value.ToString(), FileMode.Open)))
            {
                try
                {
                    FileInfo fi = new FileInfo(value.ToString());
                    byte[] bytes = reader.ReadBytes((int)fi.Length);
                    reader.Close();

                    bitmapImage = new BitmapImage();
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;

                    bitmapImage.BeginInit();
                    bitmapImage.StreamSource = new MemoryStream(bytes);
                    bitmapImage.EndInit();
                }
                catch (Exception) { }
            }
            return bitmapImage;
        }
    }
}
